package cn.hebutrun.oulabot.service.impl;


import cn.hebutrun.oulabot.common.Constants;
import cn.hebutrun.oulabot.common.util.BotUtil;
import cn.hebutrun.oulabot.entity.BaseEntity;
import cn.hebutrun.oulabot.entity.Todo;
import cn.hebutrun.oulabot.entity.enums.MessageTypeEnum;
import cn.hebutrun.oulabot.entity.response.BotMessageResponse;
import cn.hebutrun.oulabot.mapper.TodoMapper;
import cn.hebutrun.oulabot.service.ITodoService;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 待办表 服务实现类
 *
 * @author zhaolong
 * @since 2022-09-29
 */
@Service
public class TodoServiceImpl extends ServiceImpl<TodoMapper, Todo> implements ITodoService {

  @Override
  public void onOrder(String order, BotMessageResponse botMessageResponse) {
    switch (order) {
      case "待办列表", "待办" -> sendToDoList(botMessageResponse);
      case "清空待办" -> {
        this.remove(
            Wrappers.lambdaQuery(Todo.class).eq(Todo::getUserId, botMessageResponse.getUserId()));
        BotUtil.sendMessage(
            botMessageResponse,
            StrUtil.format(Constants.AT_EXPRESSION + "清空待办成功!", botMessageResponse.getUserId()));
      }
    }
    if (order.startsWith("新增待办") || order.startsWith("新建待办") || order.startsWith("添加待办")) {
      String content = order.substring(4);
      if (StrUtil.isBlank(content)) {
        BotUtil.sendMessage(botMessageResponse, "请输入待办内容!");
        return;
      }
      this.save(
          new Todo().setUserId(String.valueOf(botMessageResponse.getUserId())).setContent(content));
      BotUtil.sendMessage(
          botMessageResponse,
          StrUtil.format(Constants.AT_EXPRESSION + "新增待办成功!", botMessageResponse.getUserId()));
    } else if (order.startsWith("删除待办")) {
      String content = order.substring(4);
      List<String> strings =
          Arrays.stream(content.split(","))
              .map(x -> List.of(x.split("，")))
              .flatMap(Collection::stream)
              .toList();
      ArrayList<Integer> numbers = new ArrayList<>();
      for (String str : strings) {
        try {
          int i = Integer.parseInt(str);
          if (i < 0) {
            throw new NumberFormatException();
          }
          numbers.add(i);
        } catch (NumberFormatException e) {
          BotUtil.sendMessage(botMessageResponse, "请确认编号格式是否正确!");
          return;
        }
      }
      List<Todo> todoList =
          this.list(
              Wrappers.lambdaQuery(Todo.class)
                  .select(BaseEntity::getId)
                  .eq(Todo::getUserId, botMessageResponse.getUserId())
                  .orderByDesc(BaseEntity::getUpdateTime));

      List<String> idList =
          numbers.stream()
              .filter(x -> x - 1 < todoList.size() && x > 0)
              .map(x -> todoList.get(x - 1).getId())
              .toList();
      if (idList.size() == 0) {
        BotUtil.sendMessage(botMessageResponse, "请确认编号是否正确!");
        return;
      }
      this.removeByIds(idList);
      BotUtil.sendMessage(
          botMessageResponse,
          StrUtil.format(Constants.AT_EXPRESSION + "删除待办成功!", botMessageResponse.getUserId()));
      sendToDoList(botMessageResponse);
    } else if (order.startsWith("修改待办") || order.startsWith("编辑待办")) {
      String paramStr = order.substring("修改待办".length());
      String numberStr = paramStr.substring(0, 1);
      String content = paramStr.substring(1);
      int number;
      try {
        number = Integer.parseInt(numberStr);
      } catch (NumberFormatException e) {
        BotUtil.sendMessage(botMessageResponse, "请确认编号格式是否正确!");
        return;
      }
      Todo one =
          this.getOne(
              Wrappers.lambdaQuery(Todo.class)
                  .select(BaseEntity::getId)
                  .eq(Todo::getUserId, botMessageResponse.getUserId())
                  .orderByDesc(BaseEntity::getUpdateTime)
                  .last(StrUtil.format("limit {},1", number - 1)));
      if (ObjectUtil.isNull(one)) {
        BotUtil.sendMessage(botMessageResponse, "请确认编号是否正确!");
        return;
      }
      this.updateById(one.setContent(content));
      BotUtil.sendMessage(
          botMessageResponse,
          StrUtil.format(Constants.AT_EXPRESSION + "修改待办成功!", botMessageResponse.getUserId()));
    }
  }

  private void sendToDoList(BotMessageResponse botMessageResponse) {
    List<Todo> todoList =
        this.list(
            Wrappers.lambdaQuery(Todo.class)
                .eq(Todo::getUserId, botMessageResponse.getUserId())
                .orderByDesc(BaseEntity::getUpdateTime));
    StringBuilder sb = new StringBuilder();
    if (MessageTypeEnum.PRIVATE.getType().equals(botMessageResponse.getMessageType())) {
      sb.append(botMessageResponse.getSender().getNickname());
    } else {
      sb.append(BotUtil.getCQAtStr(botMessageResponse.getUserId()));
    }
    sb.append("\n");
    for (int i = 0; i < todoList.size(); i++) {
      sb.append(i + 1).append(". ").append(todoList.get(i).getContent()).append("\n");
    }
    if (todoList.size() == 0) {
      sb.append("暂无待办");
    }
    BotUtil.sendMessage(botMessageResponse, sb.toString().trim());
  }
}
